package com.foreveross.proxyip.core.pools.validate;

import org.apache.http.params.HttpParams;

import com.foreveross.proxyip.core.BaseCode;
import com.foreveross.proxyip.core.redis.PiRedisExecption;
import com.foreveross.proxyip.entity.ChannelEntity;
import com.foreveross.proxyip.entity.ProxyIpBean;

public class ChannelTestProxyIp extends TestProxyIp {
	AbsHandtailorValidate handtailor = null;
	
	String url = null ;
	ChannelEntity channelEntity;
	public ChannelTestProxyIp(String poolSign,ChannelEntity entity) throws NumberFormatException, PiRedisExecption{
		super(poolSign);
		this.channelEntity = entity;
		setConfig();
	}
	
	
		
		public String getConnectUrl(){
			return channelEntity.getValidDefaultUrl();
		}

		@Override
		public void setConfig() throws NumberFormatException, PiRedisExecption {
			Integer channelConnectTimeout = Integer.parseInt( BaseCode.getValue("CHANNEL_CONNECT_TIMEOUT"));
			
			Integer channelSoTimeout = Integer.parseInt(BaseCode.getValue("CHANNEL_SO_TIMEOUT")); 
			
			Integer channelMaxUsedCount = Integer.parseInt( BaseCode.getValue("CHANNEL_MAX_USED_COUNT")); 
			
			Integer valiSeparTime = Integer.parseInt(BaseCode.getValue("CHANNEL_IP_VALI_SEPAR_TIME")); 
			
			Long ipAvailTime = Long.parseLong(BaseCode.getValue("CHANNEL_IP_AVAIL_TIME")); 
			
			super.connectTimeout = channelConnectTimeout;
			super.soTimeout= channelSoTimeout;
			super.maxUsedCount = channelMaxUsedCount;
			super.valiSeparTime = valiSeparTime;
			super.ipAvailTime = ipAvailTime;
			super.proxyValiType = channelEntity.getIsValid();
			String speedGradesStr = BaseCode.getValue("SPEED_GRADE");
			this.setSpeedGrades(speedGradesStr);
		}
	/**
	 * ProxyIpBean加入标识	，该渠道池不可用
	 */
		@SuppressWarnings("unchecked")
		@Override
		public void setRefuse(ProxyIpBean proxyIp){
			
			proxyIp.getRefuseChannel().add(poolSign);
		}
		
		/**
		 * 渠道要求的速度等级大于该ip等级，则验证不通过
		 */
		@Override
		public boolean checkSpeed(ProxyIpBean proxyIp){
			Boolean bool = this.channelEntity.getSpeedGrade() > proxyIp.getSpeedGrade();
			
			if(bool){
				log.debug("渠道{}速度验证:{}", poolSign, bool);
			}
			
			return bool;
		}

		@Override
		public boolean isValidate() {
			Integer isValid = this.channelEntity.getIsValid();
			
			if(isValid==null||isValid==0){
				return false;
			}else{
				return true;
			}
		}
		@Override
		public boolean proxyConnect(ProxyIpBean proxyIp,String url,HttpParams httpParams) throws Exception {
			if(this.channelEntity.getIsValid()!=null&&channelEntity.getIsValid()==2){
				handtailor = handtailor==null?(AbsHandtailorValidate)Class.forName(channelEntity.getHandtailorClass()).newInstance():handtailor;
				return handtailor.proxyConnect(proxyIp, httpParams);
			}else{
				return super.proxyConnect(proxyIp, url, httpParams);
			}
		}

}
